package com.piper.spring.model;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;

import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 请求数据封装
 */
@Data
public class RequestData implements Serializable {

    private String ip;

    private String url;

    private JSONObject data;

    public RequestData() {
    }

    public RequestData(String ip, String url, JSONObject data) {
        this.ip = ip;
        this.url = url;
        this.data = data;
    }

    public RequestData(String url, JSONObject data) {
        this.url = url;
        this.data = data;
    }

    public String[] getStringArray(String key) {
        String values = this.data.getString(key);
        return Objects.isNull(values) ? new String[0] : values.split(",");
    }

    public Object[] getObjectArray(String key) {
        JSONArray jsonArray = this.data.getJSONArray(key);
        return Objects.isNull(jsonArray) ? new Object[0] : jsonArray.toArray();
    }

    public <T> T[] getArray(String key, T[] array) {
        JSONArray jsonArray = this.data.getJSONArray(key);
        return Objects.isNull(jsonArray) ? array : jsonArray.toArray(array);
    }

    public <T> List<T> getList(String key, Class<T> clazz) {
        return this.data.getJSONArray(key).toJavaList(clazz);
    }

    public Object get(String key) {
        JSONArray jsonArray = this.data.getJSONArray(key);
        return jsonArray.get(0);
    }

    public String getString(String key) {
        JSONArray jsonArray = this.data.getJSONArray(key);
        Object o = jsonArray.get(0);
        if (o instanceof String && Objects.nonNull(o)) return String.valueOf(o);
        return null;
    }

    public Integer getInteget(String key) {
        JSONArray jsonArray = this.data.getJSONArray(key);
        Object o = jsonArray.get(0);
        if (o instanceof Integer && Objects.nonNull(o)) return (Integer) jsonArray.get(0);
        return null;
    }

    public Double getDouble(String key) {
        JSONArray jsonArray = this.data.getJSONArray(key);
        Object o = jsonArray.get(0);
        if (o instanceof Double && Objects.nonNull(o)) return (Double) jsonArray.get(0);
        return null;
    }

    public Map<String, Object> parseMap() {
        return this.data.getInnerMap();
    }

}
